<?php
namespace app\admin\controller;
use app\admin\model\AdminCate;
use app\admin\model\PersonRole;
use think\Db;
use think\Session;
use app\admin\model\Admin as AdminModel;
use app\admin\model\Overtime as OvertimeModel;

/**
 * add by XiaHB
 * Class Overtime
 * @package app\admin\controller
 */
class Overtime extends Permissions {
    /**
     * 加班个人申请页
     * @return mixed
     */
    public function index(){
        // 获取当前登录用户ID
        $userId = Session::get('admin');
        if(empty($userId) || !isset($userId)){
            return $this->error("未获取到用户信息，请重新登录！");
        }

        $adminModel = new AdminModel();

        // 获取所有部门
        $sectionCate = Db::name('admin_cate')->where('is_prd', 0)->column('name','id');

        // 获取当前用户所在部门id
        $userCateId = Db::name('admin_cate_relation')->where('admin_id', $userId)->value('cate_id');

        // 所有项目名称
        $projectName = Db::name('project')->column('project_name','project_id');

        $userInfo = $adminModel->where(["id" => $userId])->find();
        $nickName = $userInfo['nickname'];
        $userRelation = $adminModel->where('is_prd', 0)->column('nickname','id');
        $this->assign("nickName", $nickName);
        $this->assign("userRelation", $userRelation);
        $this->assign("sectionCate", $sectionCate);
        $this->assign("projectName", $projectName);
        $this->assign("cate_id", $userCateId);
        $this->assign("user_id", $userId);
        return $this->fetch("overtime/index");
    }

    /**
     * 加班申请提交
     */
    public function publish(){
        $adminModel = new AdminModel();
        $adminCateModel = new AdminCate();
        $projectModel = new \app\admin\model\Project();
        // 获取当前登录用户ID
        $userId = Session::get('admin');// 提交人id
        if(empty($userId) || !isset($userId)){
            echo 1;exit();// 未获取到用户信息，请重新登录
        }

        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $beginTime = $post['begin_time'];// 加班申请开始时间
            $endTime = $post['end_time'];// 加班申请结束时间
            $account = $post['account'];// 加班说明
            $approvalId = $post['relation_id'];// 审批人id
            $cateId = $post['cate_id'];// 部门id
            $bagId = $post['user_id'];// 申请人id（可以是自己提也可以是别人帮着提）
            $projectId = $post['project_id'];// 项目id

            if(empty($beginTime) || empty($endTime) || empty($account) || !isset($beginTime) || !isset($endTime) || !isset($account)){
                echo 2;exit();// 参数缺失，请重试
            }
            if($beginTime >= $endTime) {
                echo 3;exit();// 请选择有效的时间范围区间
            }

            $applyName = $adminModel->where('id', $userId)->value('nickname');
            $approvalName = $adminModel->where('id', $approvalId)->value('nickname');
            $bagName = $adminModel->where('id', $bagId)->value('nickname');

            $cateName = $adminCateModel->where('id', $cateId)->value('name');// 部门名称

            if(!empty($projectId)){
                $projectName = $projectModel->where('project_id', $projectId)->value('project_name');// 项目名称
            }else{
                $projectName = '其他';
            }

            // 计算间隔时长
            $beginTimeNew = strtotime($beginTime);
            $endTimeNew = strtotime($endTime);
            $sec = $endTimeNew - $beginTimeNew;
            $sec = round($sec/60);
            $min = str_pad($sec%60, 2, 0, STR_PAD_LEFT);
            $hours_min = floor($sec/60);
            if(30 == $min){
                $duration = $hours_min + '.5';
            }else{
                $duration = $hours_min;
            }

            $insertArray = [
                'apply_id' => $bagId,// 申请人id
                'apply_name' => $bagName,// 申请人id
                'approval_id' => $approvalId,// 审批人id
                'approval_name' => $approvalName,// 审批人id
                'start_time' => $beginTime,// 申请开始时间
                'end_time' => $endTime,// 申请结束时间
                'duration' =>$duration,// 本次加班时长
                'content' => trim($account),// 加班说明
                'bag_id' => $userId,
                'cate_id' => $cateId,
                'project_id' => $projectId,
                'cate_name' => $cateName,
                'bag_name' => $applyName,
                'project_name' => $projectName,
                'status' => 1,// 状态（初始）
                'application_type' => 0,
                'type' => 1,
                'is_show' => 1,
                'create_time' => time(),
                'update_time' => time()
            ];

            if($duration < 2) {
                echo 5;exit();// 加班时长不满2小时，请勿提交
            }

            $insertId = Db::table('tplay_overtime')->insertGetId($insertArray);
            if(!$insertId){
                echo 4;exit();// 提交失败，请重试
            }else{
                return $this->success("加班时长： $duration 小时提交成功！",'admin/overtime/mylist');
            }
        } else {
            return $this->error("非法请求！");
        }
    }

    /**
     * @return mixed|void
     * @throws \think\exception\DbException
     */
    public function userList(){
        // 获取当前登录用户ID
        $userId = Session::get('admin');
        if(empty($userId) || !isset($userId)){
            return $this->error("未获取到用户信息，请重新登录！");
        }

        $overtimeModel = new OvertimeModel();
        $post = $this->request->param();
        $where['apply_id'] = $userId;// 申请人id
        $where['type'] = 1;
        $where['is_show'] = 1;
        if (isset($post['create_time']) and !empty($post['create_time'])) {
            $min_time = strtotime($post['create_time']);
            $max_time = strtotime($post['end_time']) + 24 * 60 * 60;
            $where['create_time'] = [['>=', $min_time], ['<=', $max_time]];
        }

        if (isset($post['overtime_type']) and !empty($post['overtime_type'])) {
            $where['type'] = $post['overtime_type'];
        }

        if (isset($post['audit_type']) and !empty($post['audit_type'])) {
            $where['status'] = $post['audit_type'];
        }

        $statusArray = [
            '1' => '待审批',
            '2' => '已审批',
            '3' => '驳回',
            '4' => '已使用',
            '5' => '已过期',
        ];

        $overtimeType = [
            '1' => '加班',
            '2' => '请假'
        ];

        $audit = [
            '1' => '待审批',
            '2' => '已审批',
            '3' => '已驳回',
        ];

        $myList = empty($where) ? $overtimeModel->order('create_time desc')->paginate(10) : $overtimeModel->where($where)->order('create_time desc')->paginate(10, false, ['query' => $this->request->param()]);
        $durationData = Db::name('overtime_personal')->where('user_id', $userId)->find();
        $this->assign('myList', $myList);
        $this->assign('duration_all', (!empty($durationData['overtime_all']))?$durationData['overtime_all']:0);
        $this->assign('duration_un', (!empty($durationData['overtime_available']))?$durationData['overtime_available']:0);// 未使用
        $this->assign('durationAll_used', (!empty($durationData['overtime_used']))?$durationData['overtime_used']:0);// 已使用
        $this->assign('durationAll_out', (!empty($durationData['overtime_false']))?$durationData['overtime_false']:0);
        $this->assign('status_all', $statusArray);
        $this->assign('overtime_type', $overtimeType);
        $this->assign('audit', $audit);
        return $this->fetch("overtime/user_list");
    }

    /**
     * @return mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function myList(){
        // 获取当前登录用户ID
        $userId = Session::get('admin');
        if(empty($userId) || !isset($userId)){
            return $this->error("未获取到用户信息，请重新登录！");
        }

        $overtimeModel = new OvertimeModel();
        $post = $this->request->param();
        $where['is_show'] = 1;

        if (isset($post['create_time']) and !empty($post['create_time'])) {
            $min_time = strtotime($post['create_time']);
            $max_time = strtotime($post['end_time']) + 24 * 60 * 60;
            $where['create_time'] = [['>=', $min_time], ['<=', $max_time]];
        }

        if (isset($post['overtime_type']) and !empty($post['overtime_type'])) {
            $where['type'] = $post['overtime_type'];
        }

        if (isset($post['audit_type']) and !empty($post['audit_type'])) {
            $where['status'] = $post['audit_type'];
        }

        $statusArray = [
            '1' => '待审批',
            '2' => '已审批',
            '3' => '驳回',
            '4' => '已使用',
            '5' => '已过期',
        ];

        $overtimeType = [
            '1' => '加班',
            '2' => '请假'
        ];

        $audit = [
            '1' => '待审批',
            '2' => '已通过',
            '3' => '驳回',
        ];

        $myList = empty($where) ? $overtimeModel->order('create_time desc')->paginate(10) : $overtimeModel->where($where)->order('create_time desc')->paginate(10, false, ['query' => $this->request->param()]);
        $durationData = Db::name('overtime_personal')->where('user_id', $userId)->find();
        $this->assign('myList', $myList);
        $this->assign('duration_all', (!empty($durationData['overtime_all']))?$durationData['overtime_all']:0);
        $this->assign('duration_un', (!empty($durationData['overtime_available']))?$durationData['overtime_available']:0);// 未使用
        $this->assign('durationAll_used', (!empty($durationData['overtime_used']))?$durationData['overtime_used']:0);// 已使用
        $this->assign('durationAll_out', (!empty($durationData['overtime_false']))?$durationData['overtime_false']:0);
        $this->assign('status_all', $statusArray);
        $this->assign('overtime_type', $overtimeType);
        $this->assign('audit', $audit);
        return $this->fetch("overtime/list");
    }

    /**
     * 以人为维度统计数据
     * @return mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function authorityList(){
        // 获取当前登录用户ID
        $userId = Session::get('admin');
        if(empty($userId) || !isset($userId)){
            return $this->error("未获取到用户信息，请重新登录！");
        }

        $overtimeModel = new OvertimeModel();
        $post = $this->request->param();
        $where['is_show'] = 1;
        if(!empty($post['apply_username']) && isset($post['apply_username'])) {
            $userName = trim($post['apply_username']);
            $where['apply_name'] = array('like', "%$userName%");
        }

        $myList = empty($where) ? $overtimeModel->field('apply_name, apply_id, cate_name')->group('apply_id')->paginate(10) : $overtimeModel->field('apply_name, apply_id, cate_name')->group('apply_id')->where($where)->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($myList as &$value){
            // 总申请的加班时长
            $value['overtime_all'] = Db::name('overtime')->where(array('apply_id'=>$value['apply_id'], 'type'=>1, 'is_show'=>1))->sum('duration');
            // 已批准的加班总时长
            $value['overtime_allow_all'] = Db::name('overtime')->where(array('apply_id'=>$value['apply_id'], 'type'=>1, 'status'=>2, 'is_show'=>1))->sum('duration');
            // 总申请的调休时长
            $value['application_all'] = Db::name('overtime')->where(array('apply_id'=>$value['apply_id'], 'type'=>2, 'is_show'=>1))->sum('duration');
            $personalInfo = Db::name('overtime_personal')->where('user_id', $value['apply_id'])->find();
            // 查询已使用加班时长
            $value['overtime_used'] = (!empty($personalInfo['overtime_used']) && isset($personalInfo['overtime_used']))?$personalInfo['overtime_used']:0;
            // 查询可用加班时长
            $value['overtime_available'] = (!empty($personalInfo['overtime_available']) && isset($personalInfo['overtime_available']))?$personalInfo['overtime_available']:0;
            // 已批准调休时长
            $value['application_allow_all'] = Db::name('overtime')->where(array('apply_id'=>$value['apply_id'], 'type'=>2, 'status'=>2))->sum('duration');

        }
        $this->assign('myList', $myList);
        return $this->fetch("overtime/authority_list");
    }

    /**
     * @return mixed|void
     * @throws \think\exception\DbException
     */
    public function auditList(){
        // 获取当前登录用户ID
        $userId = Session::get('admin');
        if(empty($userId) || !isset($userId)){
            return $this->error("未获取到用户信息，请重新登录！");
        }

        // 只有特定权限的人员能使用此功能
        $overtimeModel = new OvertimeModel();
//        $post = $this->request->param();
        $where['status'] = 1;
        $where['is_show'] = 1;
        $where['approval_id'] = $userId;

        $post = $this->request->param();
        if(!empty($post['apply_username']) && isset($post['apply_username'])) {
            $userName = trim($post['apply_username']);
            $where['apply_name'] = array('like', "%$userName%");
        }

        $myList = $overtimeModel->where($where)->order('create_time desc')->paginate(10, false, ['query' => $this->request->param()]);
        $this->assign('myList', $myList);
        return $this->fetch("overtime/auditList");

    }

    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function pass(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
        }
        $id = $post['id'];
        $info = Db::name('overtime')->where('id', $id)->find();
        if($info['type'] == 1){
            $info_personal = Db::name('overtime_personal')->where('user_id', $info['apply_id'])->find();
            if($info_personal){
                $time_all_old = $info_personal['overtime_all'];// 原表里的加班总时长
                $overtime_available_old = $info_personal['overtime_available'];// 原表里的可用时长
                Db::name('overtime_personal')->where('id', $info_personal['id'])->update(array('overtime_all'=> $time_all_old+$info['duration'], 'overtime_available'=>$overtime_available_old + $info['duration'] ));
            }else{
                Db::name('overtime_personal')->insert(array(
                    'user_id' => $info['apply_id'],
                    'overtime_all' => $info['duration'],
                    'overtime_used' => 0,
                    'overtime_available' => $info['duration'],
                    'overtime_false' => 0,
                    'create_time' => time(),
                    'update_time' => time(),
                ));
            }
        }else {
            // 请假申请，对数据进行对应减除
            $info_personal_new = Db::name('overtime_personal')->where('user_id', $info['apply_id'])->find();
            $overtime_used_old = $info_personal_new['overtime_used'];// 已用加班时长
            $overtime_available = $info_personal_new['overtime_available'];// 可用加班时长
            Db::name('overtime_personal')->where('user_id', $info['apply_id'])->update(array('overtime_used'=> $overtime_used_old+$info['duration'], 'overtime_available'=>$overtime_available - $info['duration']));
        }
        $res = Db::name('overtime')->where('id', $id)->update(['status'=>2]);
        if($res){
            echo 1;exit();
        }else{
            echo 2;exit();
        }
    }

    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function fail(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
        }
        $id = $post['id'];
        $info = Db::name('overtime')->where('id', $id)->update(['status'=>3]);
        if($info){
            echo 1;exit();
        }else{
            echo 2;exit();
        }
    }

    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete(){
        if ($this->request->isAjax()) {
            $post = $this->request->param();
        }
        $id = $post['id'];
        $overtimeInfo = Db::name('overtime')->where('id', $id)->find();
        if($overtimeInfo && $overtimeInfo['status'] == 2) {
            echo 3;exit();
        }
        $info = Db::name('overtime')->where('id', $id)->update(['is_show'=>0]);
        if($info){
            echo 1;exit();
        }else{
            echo 2;exit();
        }
    }
}
